/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.space.house.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.mybatis.SpliceQueryWrapper;
import com.fuyao.cloud.common.excel.annotation.RequestExcel;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.common.security.service.CloudUser;
import com.fuyao.cloud.common.security.util.SecurityUtils;
import com.fuyao.cloud.space.dto.RoomSearchHouse;
import com.fuyao.cloud.space.entity.RoomHouse;
import com.fuyao.cloud.space.house.service.RoomHouseService;
import com.fuyao.cloud.space.vo.ExcelImportHouseVO;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * 房屋信息表
 *
 * @author liyue
 * @date 2021-11-12 14:46:49
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/fyroomhouse" )
@Api(value = "fyroomhouse", tags = "房屋信息表管理")
public class RoomHouseController {

    private final RoomHouseService fyRoomHouseService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param entity 房屋信息表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('house_fyroomhouse_view')" )
    public R getFyRoomHousePage(Page page, RoomSearchHouse entity) {
        return R.ok(fyRoomHouseService.page(page, SpliceQueryWrapper.spliceSearchCondition(entity)));
    }

	/**
	 * house树查询
	 * @param page 分页对象
	 * @param id
	 * @param affiliName
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/tree/page/{id}/{affiliName}" )
	@PreAuthorize("@pms.hasPermission('house_fyroomhouse_view')" )
	public R getHouseTreePage(Page page, @PathVariable("id") Long id,@PathVariable("affiliName") String affiliName) {
		return R.ok(fyRoomHouseService.getTreePage(page, id, affiliName));
	}


    /**
     * 通过id查询房屋信息表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('house_fyroomhouse_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(fyRoomHouseService.getById(id));
    }

	@ApiOperation(value = "通过code查询", notes = "通过code查询")
    @GetMapping("/getCodeObj/{code}" )
    public R getCodeObj(@PathVariable("code" ) String code) {
        return R.ok(fyRoomHouseService.list(Wrappers.<RoomHouse>lambdaQuery().eq(RoomHouse::getCode, code)));
    }

    /**
     * 新增房屋信息表
     * @param fyRoomHouse 房屋信息表
     * @return R
     */
    @ApiOperation(value = "新增房屋信息表", notes = "新增房屋信息表")
    @SysLog("新增房屋信息表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('house_fyroomhouse_add')" )
    public R save(@RequestBody RoomHouse fyRoomHouse) {
		fyRoomHouseService.save(fyRoomHouse);
        return R.ok(fyRoomHouse);
    }

    /**
     * 修改房屋信息表
     * @param fyRoomHouse 房屋信息表
     * @return R
     */
    @ApiOperation(value = "修改房屋信息表", notes = "修改房屋信息表")
    @SysLog("修改房屋信息表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('house_fyroomhouse_edit')" )
    public R updateById(@RequestBody RoomHouse fyRoomHouse) {
        return R.ok(fyRoomHouseService.updateById(fyRoomHouse));
    }

    /**
     * 通过id删除房屋信息表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除房屋信息表", notes = "通过id删除房屋信息表")
    @SysLog("通过id删除房屋信息表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('house_fyroomhouse_del')" )
    public R removeById(@PathVariable Long id) {
        return fyRoomHouseService.batchDelete(Collections.singletonList(id));
    }

    @ApiOperation(value = "批量删除房屋信息", notes = "批量删除房屋信息")
    @SysLog("批量删除房屋信息" )
    @DeleteMapping("/batchDelete" )
    @PreAuthorize("@pms.hasPermission('house_fyroomhouse_del')" )
    public R batchDelete(@RequestBody List<Long> ids) {
        return fyRoomHouseService.batchDelete(ids);
    }

    /**
     * 导出excel 表格
     * @param entity 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('house_fyroomhouse_export')" )
    public List export(RoomSearchHouse entity) {
        return fyRoomHouseService.listHouse(SpliceQueryWrapper.spliceSearchCondition(entity));
    }

	/**
	 *  根据类型加载可选项集合
	 * @return 可选项集合
	 */
	@GetMapping("/getOptionList/{type}")
	@PreAuthorize("@pms.hasPermission('edifice_fyroomedifice_add')" )
	public R getOptionList(@PathVariable("type") String type) {
		return this.fyRoomHouseService.getOptionList(type);
	}

	/**
	 * 返回权型结构空间信息
	 * @return 树集合
	 */
	@GetMapping(value = "/tree")
	public R getTree() {
		return R.ok(fyRoomHouseService.selectTree());
	}

	/**
	 * 返回仓库类型树
	 * @return 树集合
	 */	@GetMapping(value = "/warehouseTree")
	public R warehouseTree() {
		return R.ok(fyRoomHouseService.warehouseTree());
	}

	/**
	 * 下载本地导入模板
	 * 获取本地（resources）文件
	 * @param fileName 文件名称
	 * @param response 本地文件
	 */
	@SneakyThrows
	@GetMapping("/local/{fileName}")
	public void localFile(@PathVariable String fileName, HttpServletResponse response) {
		ClassPathResource resource = new ClassPathResource("file/" + fileName);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IoUtil.copy(resource.getInputStream(), response.getOutputStream());
	}

	/**
	 * 导入房屋信信息
	 * @param excelVOList 区域列表
	 * @param bindingResult 错误信息列表
	 * @return R
	 */
	@PostMapping("/import")
	@PreAuthorize("@pms.hasPermission('edifice_fyroomedifice_export')")
	public R importRegional(@RequestExcel List<ExcelImportHouseVO> excelVOList, BindingResult bindingResult) {
		return this.fyRoomHouseService.importHouse(excelVOList, bindingResult);
	}

	/**
	 * 懒加载树
	 * @return 树集合
	 */
	@GetMapping(value = "/lazyTree/{houseId}")
	public R getLazyTree(@PathVariable("houseId") Long houseId) {
		return R.ok(fyRoomHouseService.lazyTree(houseId));
	}

	@PostMapping("/create")
	@PreAuthorize("@pms.hasPermission('edifice_fyroomedifice_add')")
	public R create() {
		CloudUser user = SecurityUtils.getUser();
		RoomHouse roomHouse = RoomHouse.builder()
				.unid(UUID.randomUUID().toString())
				.elevator("0")
				.dangerous("0")
				.construction("0")
				.belongouinfoId(user.getDeptId()).build();
		return R.ok(roomHouse);
	}
}
